package com.zzgc.modules.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.zzgc.common.entity.SchoolGradeClass;
import com.zzgc.common.entity.Student;
import com.zzgc.common.response.HttpStatus;
import com.zzgc.common.response.Result;
import com.zzgc.common.utils.*;
import com.zzgc.modules.param.Sort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 班级管理
 *
 * @Author:
 * @CreateTime: 2022-11-24  11:23
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("class")
@Api(tags = "班级管理")
public class ClassController extends BaseController {

    @GetMapping("getList")
    @ApiOperation(value = "根据条件,获取班级列表", notes = "获取班级列表")
    public Result getClasses(SchoolGradeClass gradeClass) {
        // 查询本校的班级
        gradeClass.setSSchoolId(Long.valueOf(getSchoolId()));
        // 排序
        gradeClass.setSorts(Arrays.asList(new Sort("s_sort")));
        if (gradeClass.getSYear() == null){
            gradeClass.setSYear(getsYear() + "");
        }
        List<SchoolGradeClass> classList = schoolGradeClassService.queryByPageByYear(gradeClass);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", classList.size() == 0 ? 0 : classList.get(0).getTotal());
        for (SchoolGradeClass schoolGradeClass : classList) {
            Student student = new Student();
            student.setSClassId(schoolGradeClass.getId());
            long count = studentService.count(student);
            schoolGradeClass.setTotal(count);
        }
        map.put("data", classList);
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(map)
                .build();
    }

    @GetMapping("getById/{classId}")
    @ApiOperation(value = "根据id获取班级信息", notes = "获取班级信息")
    public Result getClassById(@PathVariable Long classId) {
        SchoolGradeClass schoolGradeClass = schoolGradeClassService.queryById(classId);
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(schoolGradeClass)
                .build();
    }

    @PostMapping("add")
    @ApiOperation(value = "添加班级信息", notes = "添加班级信息")
    public Result addClass(@RequestBody SchoolGradeClass gradeClass) {
        gradeClass.setSSchoolId(Long.valueOf(super.getSchoolId()));
        gradeClass.setSCreateBy(super.getUserName());
        gradeClass.setSCreateDate(new Date());
        if (gradeClass.getSName() != null){
            // 三班 去除班字得到中文数字
            String s = gradeClass.getSName().replaceAll("班", "");
            if (!LangUtil.isNumeric(s)) {
                Integer integer = LangUtil.hanZiToNum(s);
                gradeClass.setSSort(integer);
                gradeClass.setSName(integer + "班"); // 修改班级为  3班
            }else {
                gradeClass.setSSort(Integer.valueOf(s));
            }
        }
        SchoolGradeClass aClass = schoolGradeClassService.insert(gradeClass);
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(aClass)
                .build();
    }

//    @PutMapping("edit")
//    @ApiOperation(value = "编辑班级信息", notes = "编辑班级信息")
    public Result editClass(@RequestBody SchoolGradeClass gradeClass) {
        gradeClass.setSUpdateBy(super.getUserName());
        gradeClass.setSUpdateDate(new Date());
        SchoolGradeClass aClass = schoolGradeClassService.update(gradeClass);
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(aClass)
                .build();
    }

    @DeleteMapping("del/{classId}")
    @ApiOperation(value = "删除班级信息", notes = "删除班级信息")
    public Result deleteClass(@PathVariable Long classId) {
        boolean b = schoolGradeClassService.deleteById(classId);
        if (!b) {
            return Result.builder().code(500).msg("删除班级失败!").build();
        }
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg("删除班级成功!")
                .build();
    }

    @GetMapping("print")
    @ApiOperation(value = "打印班级二维码", notes = "打印班级二维码")
    public Result printClasses(Long classId, Integer number){
        Student student = new Student();
        List<Student> arrayList = new ArrayList<>();
        student.setSSchoolId(Long.valueOf(super.getSchoolId()));
        student.setSClassId(classId);
        student.setSize(Integer.MAX_VALUE);
        List<Student> students = studentService.queryByPage(student);
//        File file = new File(qrcodePath);
//        if (!file.exists()){
//            file.mkdirs();
//        }
//        File file1 = new File(printFilePath + classId);
//        if (!file1.exists()){
//            file1.mkdirs();
//        }
        File file = new File(qrcodePath); // 没有此路径就创建
        if (!file.exists()) {
            file.mkdirs();
        }
        for (Student student1 : students) {
            String sIdCard = student1.getSIdCard();
            String codePath = qrcodePath + sIdCard + ".jpg";
//            System.out.println("student1 = " + student1);
//            // 生成二维码
//            ZxingUtils.getQRCodeImge(super.getUserRegionId() + "_" + student1.getId() + "_" + number, 200, codePath);
            ZxingUtils.getQRCodeImge(String.valueOf(student1.getSStudentId()), 200, codePath);
//            // 填充模板, 生成视力筛查卡
//            pdfOut(student1, codePath);
//            arrayList.add(ImageIO.read(new File(printFilePath + sIdCard + ".jpg")));
            student1.setTableName("/oss/qrcode/" + sIdCard + ".jpg");
            arrayList.add(student1);
        }
        // 合并图片, 每6张合成一张
        List<List<Student>> lists = MergePdfFiles.mySubList(arrayList);
//        for (int i = 0; i < lists.size(); i++) {
//            BufferedImage image = MergePdfFiles.mergeImage(true, lists.get(i));
//            ImageIO.write(image, "png", new File(printFilePath + classId + "/" + i + ".png"));
//        }
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(lists)
                .build();
    }

    public void pdfOut(Student student, String imgPath) {
        // 模板地址
        String tempPath = pdfTemplatePath + "pdfTemplate.pdf";
        // 生成pdf后的保存地址
        String outTempPath = printFilePath + student.getSIdCard() + ".pdf";
        File old = new File(outTempPath);
        if (old.exists()) {
            old.delete();
        }

        PdfReader reader = null;
        FileOutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper pdfStamper = null;

        try {
            // 读取pdf模板
            reader = new PdfReader(tempPath);
            // 将填充完成后的pdf输出到指定位置
            out = new FileOutputStream(outTempPath);
            bos = new ByteArrayOutputStream();
            pdfStamper = new PdfStamper(reader, bos);

            // 获取到表单集合
            AcroFields acroFields = pdfStamper.getAcroFields();
            // 加载字体
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 设置写入字体
            acroFields.addSubstitutionFont(font);

            // 设置文本信息
            acroFields.setField("school", student.getSSchoolName());
            acroFields.setField("name", student.getSName());
            acroFields.setField("grade", student.getSGradeName());
            acroFields.setField("class", student.getSClassName());
            acroFields.setField("studentNum", student.getSStudentNum());

//            String time = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 "));
//            acroFields.setField("datetime", time);

            // 根据地址读取需要放入pdf中的图片
            Image image = Image.getInstance(imgPath);

            // 设置图片在哪一页
            PdfContentByte overContent = pdfStamper.getOverContent(acroFields.getFieldPositions("image").get(0).page);
            // 获取模板中图片域的大小
            Rectangle signRect = acroFields.getFieldPositions("image").get(0).position;
            float x = signRect.getLeft();
            float y = signRect.getBottom();
            // 图片等比缩放
            image.scaleAbsolute(signRect.getWidth(), signRect.getHeight());
            // 图片位置
            image.setAbsolutePosition(x, y);
            // 在该页加入图片
            overContent.addImage(image);

            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            pdfStamper.setFormFlattening(true);
            pdfStamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importedPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importedPage);
            doc.close();
            try {
                // 转换pdf为jpg, 并画上边框
                Pdf2JpgHelper.pdf2jpg(outTempPath, printFilePath + student.getSIdCard() + ".jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
                out.close();
                bos.close();
                pdfStamper.close();
            } catch (IOException | DocumentException e) {
                e.printStackTrace();
            }
        }
    }

}
